<?php

class ArticleController extends AdminController {

	//public $First="121211";
	public function init() {
		parent::init();
		$this->mediaConfig = 'image';
	}

	const MODEL_CLASS_NAME = 'Article';

	public function actionIndex() {
		$model = new Article(Article::SCENARIO_SEARCH);

		$model->unsetAttributes();  // clear any default values

		if (isset($_GET[self::MODEL_CLASS_NAME])) {
			$model->attributes = $_GET[self::MODEL_CLASS_NAME];
			Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, $_GET[self::MODEL_CLASS_NAME]);
		} else if (isset($_POST[self::MODEL_CLASS_NAME])) {
			$model->attributes = $_POST[self::MODEL_CLASS_NAME];
			Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, $_POST[self::MODEL_CLASS_NAME]);
		} else {
			$articleState = Yii::app()->user->getState(app()->controller->id . self::MODEL_CLASS_NAME);
			if ($articleState != null)
			$model->attributes = $articleState;
		}

		$this->render('index', array(
	    'model' => $model,
		));
	}

	function actions() {
		return array(
	    'update' => array(
		'class' => 'lib.components.actions.UpdateAction',
		'modelClass' => self::MODEL_CLASS_NAME,
		'validateMethod' => 'validateUpdate',
		'callback' => 'resetCheckOutStatus',
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => 'Article')))
		),
	    'create' => array(
		'class' => 'lib.components.actions.CreateAction',
		'modelClass' => self::MODEL_CLASS_NAME,
		'messages' => array('success' => t('MSG_INFO_INSERT_SUCCESS', 'messages', array('{0}' => 'Article')))
		),
	    'trash' => array(
		'class' => 'lib.components.actions.DeleteAction',
		'customAction' => 'trash',
		'confirmMessages' => t('MSG_TRASH', 'messages'),
		),
	    'checkin' => array(
		'class' => 'lib.components.actions.DeleteAction',
		'customAction' => 'checkin',
		'confirmMessages' => t('MSG_CHECK_IN', 'messages'),
		),
	    'error' => array(
		'class' => 'lib.components.actions.ErrorAction',
		),
	    'delete' => array(
		'class' => 'lib.components.actions.DeleteAction',
		'ajaxView' => "//share/_delete_article",
		'messages' => array('success' => t('MSG_INFO_DELETE_SUCCESS', 'messages', array('{0}' => t('LBL_ARTICLE', 'article'))))
		),
	       'status' => array(
		'class' => 'lib.components.actions.LGUpdateAnItemAction',
		'customAction' => 'changeStatus',
		'modelClass' => self::MODEL_CLASS_NAME,
		'itemName' => t('LBL_ARTICLE', 'article'),
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_ARTICLE', 'article'))))
		),
	         'featured' => array(
		'class' => 'lib.components.actions.LGUpdateAnItemAction',
		'customAction' => 'changeFeature',
		'modelClass' => self::MODEL_CLASS_NAME,
		'itemName' => t('LBL_ARTICLE', 'article'),
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_ARTICLE', 'article'))))
		),
		);
	}

	public function resetCheckOutStatus($model) {
		$model->checkout = 0;
		$model->save();
	}

	public function actionRefresh() {
		Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, null);
		$this->redirect(url(app()->controller->id . "/index"));
	}

	/**
	 * Validate before edit article.
	 *
	 * @param type $model
	 * @return \LGMessage If articel
	 */
	public function validateUpdate($model) {

		$msg = NULL;
		if (isset($_POST[self::MODEL_CLASS_NAME])) {
			//When user click save buttons
			$lastUpdateDate = $_POST['lastUpdateDate'];

			$updateDate = $model->update_date;
			//If last update date of model in database == last update date of model on client
			if ($model->checkout == Yii::app()->user->id && $lastUpdateDate == $model->update_date) {

				//If checkout == 0 => It means that someone unchecked in this article.
				//So current user can not update this article
				if ($model->checkout == 0) {
					$msg = new LGMessage(MsgType::WARNING, t('CHECK_OUT_ERROR', 'article'));
				}
			} else {
				$msg = new LGMessage(MsgType::WARNING, t('UPDATED_ERROR', 'article'));
			}
		} else {
			//When user click update
			if ($model->checkout == 0 || $model->checkout == Yii::app()->user->id) {
				if ($model->checkout == 0) {
					$model->checkout = Yii::app()->user->id;
					$model->save();
				}
			} else {
				$msg = new LGMessage(MsgType::WARNING, t('CHECK_OUT_ERROR', 'article'));
			}
		}
		return $msg;
	}

	public function actionGetLockedTooltip() {
		$id = $_POST['id'];
		$article = Article::model()->findByPk($id);
		$user = User::model()->findByPk($article->checkout);

		if ($user != null) {
			$updatedateTimeSpan = strtotime($article->update_date);
			$updatedate = date(LGConstant::DATE_FORMAT, $updatedateTimeSpan);
			$this->renderPartial('_lockedtooltip', array("user" => $user, "updatedate" => $updatedate));
		} else {
			echo t('THIS_USER_HAS_BEEN_DELETED', 'article');
		}
	}

	//    public function actionStatus($id) {
	//	if (Yii::app()->request->isAjaxRequest && $id != '') {
	//
	//	    $article = Article::model()->findByPk($id);
	//	    $article->status = ($article->status == LGConstant::PUBLISH_STATUS
	//		    ? LGConstant::UNPUBLISH_STATUS : LGConstant::PUBLISH_STATUS);
	//
	//	    if ($article->save()) {
	//		app()->end();
	//	    }
	//	}
	//    }


	/**
	 * @author Kien Tran <kien.tran@logigear.com>
	 * @param type $models
	 * @param type $action
	 * @return \LGMessage
	 */
	public function changeStatus($models, $action) {
		$msgReturn = null;
		if ($models != null && !empty($models)) {
			/* @var $article Article*/
			$article = $models[0];
			$article->scenario = Menu::SCENARIO_UPDATE;

			$newStatus = null;
			if ($article->status == LGConstant::PUBLISH_STATUS) {
				$newStatus = LGConstant::UNPUBLISH_STATUS;
				$msgStatus = t('LBL_INACTIVED');
			} else {
				$newStatus = LGConstant::PUBLISH_STATUS;
				$msgStatus = t('LBL_ACTIVED');
			}

			$isSuccess = $article->saveAttributes(array('status' => $newStatus));

			if ($isSuccess) {
				$msgReturn = new LGMessage(
				MsgType::SUCCESS, Yii::t('messages', 'MSG_INFO_SUCCESS', array('{0}' => t('LBL_ARTICLE', 'article'), '{1}' => $msgStatus))
				);
			} else {
				if ($article->getError('status') != null) {
					$msg = $article->getError('status');
				} else {
					$msg = Yii::t('messages', 'MSG_NOT_ACTIVATED', array('{0}' => t('LBL_ARTICLE', 'article'), '{1}' => $msgStatus));
				}

				$msgReturn = new LGMessage(
				MsgType::ERROR, $msg);
			}
		} else {
			$msgReturn = new LGMessage(
			sgType::ERROR, $action->messages['error']);
		}
		return $msgReturn;
	}

	//   public function actionFeatured($id) {
	//	if (Yii::app()->request->isAjaxRequest && $id != '') {
	//
	//	    $article = Article::model()->findByPk($id);
	//	    $article->featured = ($article->featured == LGConstant::YES_FEATURED ? LGConstant::NO_FEATURED : LGConstant::YES_FEATURED);
	//
	//	    if ($article->save()) {
	//		app()->end();
	//	    }
	//	}
	//    }

	/**
	 * @author Kien Tran <kien.tran@logigear.com>
	 * @param type $models
	 * @param type $action
	 * @return \LGMessage
	 */
	public function changeFeature($models, $action) {
		$msgReturn = null;
		if ($models != null && !empty($models)) {
			/* @var $article Article*/
			$article = $models[0];
			$article->scenario = Menu::SCENARIO_UPDATE;

			$newStatus = null;
			if ($article->featured == LGConstant::YES_FEATURED) {
				$newStatus = LGConstant::NO_FEATURED;
				$msgStatus = t('LBL_FEATURE');
			} else {
				$newStatus = LGConstant::YES_FEATURED;
				$msgStatus = t('LBL_FEATURE');
			}

			$isSuccess = $article->saveAttributes(array('featured' => $newStatus));

			if ($isSuccess) {
				$msgReturn = new LGMessage(
				MsgType::SUCCESS, Yii::t('messages', 'MSG_INFO_SUCCESS', array('{0}' => t('LBL_ARTICLE', 'article'), '{1}' => $msgStatus))
				);
			} else {
				if ($article->getError('featured') != null) {
					$msg = $article->getError('featured');
				} else {
					$msg = Yii::t('messages', 'MSG_NOT_ACTIVATED', array('{0}' => t('LBL_ARTICLE', 'article'), '{1}' => $msgStatus));
				}

				$msgReturn = new LGMessage(
				MsgType::ERROR, $msg);
			}
		} else {
			$msgReturn = new LGMessage(
			sgType::ERROR, $action->messages['error']);
		}
		return $msgReturn;
	}


	public function actionRestore() {
		$id = $_GET['id'];
		$article = Article::model()->findByPk($id);
		$article->status = LGConstant::PUBLISH_STATUS;
		$article->save();
	}

	public function actionDeleteForever() {
		$id = $_GET['id'];
		$article = Article::model()->findByPk($id);
		$article->delete();
	}

	public function loadModel() {
		$model = null;
		if (isset($_GET['id'])) {
			$ids = explode(',', $_GET['id']);
			if (isset($ids)) {
				$criteria = new CDbCriteria;
				$criteria->addInCondition('id', $ids);
				$model = Article::model()->findAll($criteria);
			}
		}
		return $model;
	}

	public function actionBrowse() {
		if (Yii::app()->request->isAjaxRequest) {
			$this->renderPartial('_file_browser', null, false, true);
		}
	}

	public function trash($model) {
		$msg = NULL;
		$isCheckin = true;
		foreach ($model as $m) {
			if ($m != null) {
				$m->status = LGConstant :: TRASHED_STATUS;

				if (!$m->save()) {
					$msg = new LGMessage(MsgType::SUCCESS, t('MSG_INFO_TRASH_UNSUCCESS', 'messages', array('{0}' =>  t('LBL_ARTICLE', 'article'))));
				}
			} else {
				$isCheckin = false;
				break;
			}
			if ($isCheckin) {
				$msg = new LGMessage(MsgType::SUCCESS, t('MSG_INFO_TRASH_SUCCESS', 'messages', array('{0}' => t('LBL_ARTICLE', 'article'))));
			} else {$msg = new LGMessage(MsgType::SUCCESS, t('MSG_INFO_TRASH_SUCCESS', 'messages', array('{0}' => t('LBL_ARTICLE', 'article'))));
			$msg = new LGMessage(MsgType::SUCCESS, t('MSG_INFO_TRASH_UNSUCCESS', 'messages', array('{0}' =>  t('LBL_ARTICLE', 'article'))));
			}
		}
		return $msg;
	}

	public function checkin($model) {
		$msg = NULL;
		$isCheckin = true;
		foreach ($model as $m) {
			if ($m != null) {
				$m->checkout = LGConstant :: UNCHECK_OUT;
				$m->save();
			} else {
				$isCheckin = false;
				break;
			}
			if ($isCheckin) {
				$msg = new LGMessage(MsgType::SUCCESS, t('MSG_INFO_CHECK_IN_SUCCESS', 'messages', array('{0}' => t('LBL_ARTICLE', 'article'))));
			} else {
				$msg = new LGMessage(MsgType::SUCCESS, t('MSG_INFO_CHECK_IN_UNSUCCESS', 'messages', array('{0}' => t('LBL_ARTICLE', 'article'))));
			}
		}
		return $msg;
	}


	public function actionCancelEdit($id) {
		$article = Article::model()->findByPk($id);
		$article->checkout = 0;
		$article->save();
		$this->redirect(url(app()->controller->id . '/index'));
	}

	/**
	 * If actionID is create or update, split Article Text to introtext and fulltext
	 * @param type $actionID
	 * @return type
	 */
	public function createAction($actionID) {

		//If actionID is create or update, split fulltext to introtext and fulltext
		$actions = array('create', 'update');
		if (in_array($actionID, $actions)) {

			//Get modelClass from functions actions();
			$arr = $this->actions();
			$modelClassName = $arr[$actionID]['modelClass'];
			if (isset($_POST[$modelClassName])) {
				$articleAttributes = & $_POST[$modelClassName];

				$introtext_fulltext = explode(LGConstant::ARTICLE_READ_MORE_LINE, $articleAttributes['fulltext'], 2);
				$articleAttributes['introtext'] = "";
				if (count($introtext_fulltext) == 2) {
					$articleAttributes['introtext'] = $introtext_fulltext[0];
					$articleAttributes['fulltext'] = $introtext_fulltext[1];
				}
			}
		}

		return parent::createAction($actionID);
	}


	/**
	 * Disable Comment function
	 */

	//    const RENDER = 0;
	//
	//    /**
	//     * The action will delete loaded model.
	//     */
	//    const PROCEED = 1;
	//
	//    /**
	//     * The action will cancel the delete.
	//     */
	//    const CANCEL = 2;
	//
	//    /**
	//     * @var mixed the redirect URL processed by the class method.
	//     */
	//    private $_redirectTo = null;
	//
	//    /**
	//     * @var int the status for the action to proceed with.
	//     */
	//    private $_status = self::RENDER;
	//
	//    /**
	//     * @var string the name of the AJAX view.
	//     */
	//    public $ajaxView = '//article/_common';
	//    public $ajaxViewComment = "_view_comment";
	//
	//    /**
	//     * @var string scripts which should be disabled on AJAX call.
	//     */
	//    public $disableScripts = array();
	//
	//    /**
	//     * @var string flash messages prefix.
	//     */
	//    public $flashTypePrefix = '';
	//
	//    /**
	//     * @var boolean is this an AJAX request.
	//     */
	//    protected $isAjaxRequest;
	//
	//    /**
	//     * @var array user set messages for the action.
	//     */
	//    public $messages = array();
	//
	//    /**
	//     * @var mixed the redirect URL set by the user.
	//     */
	//    public $redirectTo = null;
	//
	//    /**
	//     * @var mixed the redirect URL used after successful delete.
	//     */
	//    public $redirectToAfterDelete = array('admin');
	//
	//    /**
	//     * @var string message category used for Yii::t method.
	//     */
	//    public $tCategory = 'app';
	//
	//    /**
	//     * @var string the name of the view.
	//     */
	//    public $view = null;
	//
	//    protected function initViewComment() {
	//	// Create default messages array
	//	$defaultMessages = array(
	//	    'error' => Yii::t($this->tCategory, t('THERE_WAS_AN_ERROR_WHILE_SAVING._PLEASE_TRY_AGAIN.', 'message')),
	//	    'postRequest' => Yii::t($this->tCategory, t('ONLY_POST_REQUESTS_ARE_ALLOWED', 'message')),
	//	    'success' => Yii::t($this->tCategory, t('SUCCESSFULLY_DELETED', 'message')),
	//	);
	//
	//	// Merge with user set messages if array is provided
	//	if (is_array($this->messages)) {
	//	    $this->messages = CMap::mergeArray(
	//			    $defaultMessages, $this->messages);
	//	}
	//	else
	//	    throw new CException(Yii::t($this->tCategory, t('ACTION_MESSAGES_NEED_TO_BE_AN_ARRAY', 'message')));
	//
	//	// If view is not set, use action id for view
	//	if ($this->view === null)
	//	    $this->view = $this->id;
	//
	//	// Check if this is an AJAX request
	//	if ($this->isAjaxRequest = Yii::app()->request->isAjaxRequest) {
	//	    // Create default array for scripts which should be disabled
	//	    $defaultDisableScripts = array(
	//		'jquery.js',
	//		'jquery.min.js',
	//		'jquery-ui.min.js',
	//		'jquery.yiigridview.js'
	//	    );
	//
	//	    // Merge with user set scripts which should be disabled
	//	    if (is_array($this->disableScripts)) {
	//		$this->disableScripts = CMap::mergeArray(
	//				$defaultDisableScripts, $this->disableScripts);
	//	    }
	//	    else
	//		throw new CException(Yii::t($this->tCategory, t('DISABLE_SCRIPTS_NEED_TO_BE_AN_ARRAY.', 'message')));
	//
	//	    // Disable scripts
	//	    foreach ($this->disableScripts as $script)
	//		Yii::app()->clientScript->scriptMap[$script] = false;
	//	}
	//    }

	//    public function actionComment($id) {
	//	if (Yii::app()->request->isAjaxRequest && $id != '') {
	//
	//	    $article = Article::model()->findByPk($id);
	//	    $article->can_comment = ($article->can_comment == LGConstant::CAN_COMMENT
	//		    ? LGConstant::CAN_NOT_COMMENT : LGConstant::CAN_COMMENT);
	//
	//	    if ($article->save()) {
	//		app()->end();
	//	    }
	//	}
	//    }
	//
	//    public function loadViewCommentModel() {
	//	$model = null;
	//	if (isset($_POST['id'])) {
	//	    $ids = explode(',', $_POST['id']);
	//	    if (isset($ids)) {
	//		$criteria = new CDbCriteria;
	//		$criteria->addInCondition('id', $ids);
	//		$model = Comment::model()->findAll($criteria);
	//	    }
	//	}
	//	return $model;
	//    }

	//    public function actionApprove() {
	//	$model = $this->loadViewCommentModel();
	//	foreach ($model as $m) {
	//	    if ($m != null) {
	//		$m->status = LGConstant::COMMENT_STATUS_APPROVED;
	//		$m->save();
	//	    }
	//	}
	//    }

	//    public function actionReject() {
	//	$model = $this->loadViewCommentModel();
	//	foreach ($model as $m) {
	//	    if ($m != null) {
	//		$m->status = LGConstant::COMMENT_STATUS_REJECTED;
	//		$m->save();
	//	    }
	//	}
	//    }

	//    public function actionDeleteComment() {
	//	$model = $this->loadViewCommentModel();
	//	foreach ($model as $m) {
	//	    $m->delete();
	//	}
	//    }
	//    public function actionViewComment() {
	//	$this->initViewComment();
	//	$models = $this->loadModel();
	//	$model = $models[0];
	//
	//	$cmodel = new Comment('search');
	//	$cmodel->unsetAttributes();  // clear any default values
	//	if (isset($_GET['Comment']))
	//	    $cmodel->attributes = $_GET['Comment'];
	//	$cmodel->article_id = $model->id;
	//
	//	if ($this->isAjaxRequest) {
	//	    // Output JSON encoded content
	//	    echo CJSON::encode(array(
	//		'status' => 'render',
	//		'content' => $this->renderPartial($this->ajaxViewComment, array(
	//		    'model' => $cmodel,
	//		    'cancelUrl' => $this->getRedirectUrl($cmodel->id)), true, true),
	//	    ));
	//	    Yii::app()->end();
	//	}
	//	else
	//	    $this->render($this->view, array(
	//		'model' => $cmodel,
	//		'cancelUrl' => $this->getRedirectUrl($cmodel->id)));
	//    }

	//    /**
	//     * Returns an URL for redirect.
	//     * @param int $id the id of the model to redirect to.
	//     * @return mixed processed redirect URL.
	//     */
	//    protected function getRedirectUrl($id) {
	//	// Process redirect URL
	//	if ($this->_redirectTo === null) {
	//	    // Use default redirect URL
	//	    if ($this->redirectTo === null)
	//		$this->_redirectTo = array('view', 'id' => $id);
	//	    // User set redirect URL is an array, check if id is needed
	//	    else if (is_array($this->redirectTo)) {
	//		// ID is set
	//		if (isset($this->redirectTo['id']))
	//		// ID needed, set it to the model id
	//		    if ($this->redirectTo['id'])
	//			$this->redirectTo['id'] = $id;
	//		    // ID is not needed, remove it from redirect URL
	//		    else
	//			unset($this->redirectTo['id']);
	//
	//		// Set processed redirect URL
	//		$this->_redirectTo = $this->redirectTo;
	//	    }
	//	    // User set redirect URL is a string
	//	    else
	//		$this->_redirectTo = $this->redirectTo;
	//	}
	//
	//	// Return processed redirect URL
	//	return $this->_redirectTo;
	//    }

	//    public function initActions() {
	//	// Create default messages array
	//	 $defaultMessages = array(
	//            'cancel' => Yii::t($this->tCategory, t('DELETION_CANCELED', 'message')),
	//            'error' => Yii::t($this->tCategory,  t('THERE_WAS_AN_ERROR_WHILE_DELETING._PLEASE_TRY_AGAIN.', 'message')),
	//            'postRequest' => Yii::t($this->tCategory,  t('ONLY_POST_REQUESTS_ARE_ALLOWED', 'message')),
	//            'success' => Yii::t($this->tCategory,  t('SUCCESSFULLY_DELETED', 'message')),
	//        );
	//
	//	// Merge with user set messages if array is provided
	//	if (is_array($this->messages)) {
	//	    $this->messages = CMap::mergeArray(
	//			    $defaultMessages, $this->messages);
	//	}
	//	else
	//	    throw new CException(Yii::t($this->tCategory, t('ACTION_MESSAGES_NEED_TO_BE_AN_ARRAY', 'message')));
	//
	//	// If view is not set, use action id for view
	//	if ($this->view === null)
	//	    $this->view = $this->id;
	//
	//	// Get the action status
	//	if (isset($_POST['Confirmed']))
	//	    $this->_status = self::PROCEED;
	//	else if (isset($_POST['Canceled']))
	//	    $this->_status = self::CANCEL;
	//
	//	// Check if this is an AJAX request
	//	if ($this->isAjaxRequest = Yii::app()->request->isAjaxRequest) {
	//	    // Create default array for scripts which should be disabled
	//	    $defaultDisableScripts = array(
	//		'jquery.js',
	//		'jquery.min.js',
	//		'jquery-ui.min.js'
	//	    );
	//
	//	    // Merge with user set scripts which should be disabled
	//	    if (is_array($this->disableScripts)) {
	//		$this->disableScripts = CMap::mergeArray(
	//				$defaultDisableScripts, $this->disableScripts);
	//	    }
	//	    else
	//		throw new CException(Yii::t($this->tCategory, t('DISABLE_SCRIPTS_NEED_TO_BE_AN_ARRAY.', 'message')));
	//
	//	    // Disable scripts
	//	    foreach ($this->disableScripts as $script)
	//		Yii::app()->clientScript->scriptMap[$script] = false;
	//
	//	    // Allow only post requests
	//	    if (!Yii::app()->request->isPostRequest) {
	//		// Output JSON encoded content
	//		echo CJSON::encode(array(
	//		    'status' => 'failure',
	//		    'content' => $this->messages['postRequest'],
	//		));
	//
	//		// Stop script execution
	//		Yii::app()->end();
	//	    }
	//	}
	//    }


}